<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>C# basics</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, basics, tutorial, programming language, .NET, Mono, learn C#">
<meta name="description" content="This part of the C# tutorial covers C# basics.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Basics</h1>

<p>
In this part of the C# tutorial, we will cover basic programming concepts
of the C# language. We introduce the very basic programs. We will work with variables, 
constants and basic data types. We will read and write to the console; we will mention
variable interpolation.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
We start with a very simple code example. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine("This is C#");
    }
}
</pre>

<p>
This is our first C# program. It will print "This is C#" message to
the console. We will explain it line by line. 
</p>

<pre class="explanation">
using System;
</pre>

<p>
The <code>using</code> keyword imports a specific namespace to
our program. Namespaces are created to group and/or distinguish named entities
from other ones. This prevents name conflicts. This line is a C# statement. 
Each statement is ended with a semicolon.
</p>

<pre class="explanation">
public class CSharpApp
{
    ...
}
</pre>

<p>
Each C# program is structured. It consists of classes and its members.
A class is a basic building block of a C# program. The 
<code>public</code> keyword gives unrestricted access to this
class. The above code is a class definition. The definition has a body,
which starts with a left curly brace ({) and ends with a right curly brace (}).
</p>

<pre class="explanation">
static void Main()
{
    ...
}
</pre>

<p>
The <b class="keyword">Main()</b> is a method. A method is a piece of code
created to do a specific job. Instead of putting all code into one place,
we divide it into pieces, called methods. This brings modularity to our
application. Each method has a body, in which we place statements. The body
of a method is enclosed by curly brackets. The specific job for the Main() 
method is to start the application.
It is the entry point to each console C# program. The method is declared to be
<code>static</code>. This static method can be called without the need
to create an instance of the CSharApp class. First we need start the application
and after that, we are able to create instances of classes. 
</p>

<pre class="explanation">
Console.WriteLine("This is C#");
</pre>

<p>
In this code line, we print the "This is C#" string
to the console. To print a message to the console, we use the 
<code>WriteLine()</code> method of the <code>Console</code> class.
The class represents the standard input, output, and error streams 
for console applications. Note that Console class is part of the System namespace.
This line was the reason to import the namespace with the <code>using System;</code> 
statement. If we didn't use the statement, we would have to use the fully qualified
name of the WriteLine() method.<br>
This would be <code>System.Console.WriteLine("This is C#");</code>.
</p>

<pre>
$ ./simple.exe 
This is C#
</pre>

<p>
Executing the program gives the above output.
</p>

<hr class="btm">

<p>
<b>Reading values</b> We can use the Console class to read values as well. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        string name;

        Console.Write("Enter your name: ");
        name = Console.ReadLine();
        Console.WriteLine("Hello {0}", name);
    }
}
</pre>

<p>
The second program will read a value from a console
and print it. 
</p>

<pre class="explanation">
string name;
</pre>

<p>
We declare a variable. The variable is called 'name'. Unlike constants, 
which store only one value during the life of the program, variables may
store various different values of the same type. The <code>string</code>
keyword defines the data type of the variable. Our variable will hold 
string values.
</p>

<pre class="explanation">
name = Console.ReadLine();
</pre>

<p>
We read a line from the terminal. When we hit the Enter key, the 
input is assigned to the name variable. 
</p>


<pre class="explanation">
Console.WriteLine("Hello {0}", name);
</pre>

<p>
In this code line, we perform variable interpolation. <b>Variable interpolation</b>
is replacing variables with their values inside string literals. 
Another names for variable interpolation are: variable substitution
and variable expansion.
</p>

<pre>
$ ./readline.exe 
Enter your name: Jan Bodnar
Hello Jan Bodnar
</pre>

<p>
This is the output of the second program.
</p>


<h2>Command line arguments</h2>

<p>
C# programs can receive command line arguments. They
follow the name of the program, when we run it. 
</p>


<pre class="code">
using System;

public class CSharpApp 
{
    static void Main(string[] args) 
    {
        for (int i=0; i&lt;args.Length; i++) 
        {
            Console.WriteLine("{0}", args[i]);
        }
    }
}
</pre>

<p>
Command line arguments can be passed to the 
Main() method. 
</p>

<pre class="explanation">
public static void Main(string[] args) 
</pre>

<p>
This <code>Main()</code> method receives a string array of 
command line arguments. 
</p>

<pre class="explanation">
for (int i=0; i&lt;args.Length; i++) 
{
    Console.WriteLine("{0}", args[i]);
}
</pre>

<p>
We go through the array of these arguments
with a for loop and print them to the console.
The <code>Length</code> property gives
the number of elements in the array. Loops and
arrays will be described in more detail later.
</p>

<pre>
$ ./commandargs.exe 1 2 3
1
2
3
</pre>

<p>
We provide three numbers as command line arguments and these are
printed to the console. 
</p>

<hr class="btm">

<p>
In C# 2008 Express Edition, select project properties. 
In the Debug tab, there is a text area for specifying the command
line arguments. 
</p>

<br>
<img src="/img/lang/csharp/arguments.png" alt="Command line arguments">
<div class="figure">Figure: Command line arguments</div>
<br>


<h2>Variables and Constants</h2>

<p>
A <b>variable</b> is a place to store data. A variable
has a name and a data type. A data type determines, what values can
be assigned to the variable. Integers, strings, boolean values etc.
Over the time of the program, variables can obtain various values
of the same data type. Variables are always initialized to the
default value of their type before any reference to the variable 
can be made. Unlike variables, <b>constants</b> retain their values. Once
initialized, they cannot be modified. Constants are created with 
the <b class="keyword">const</b> keyword. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        string city = "New York";
        string name = "Paul"; int age = 35;
        string nationality = "American";

        Console.WriteLine(city);
        Console.WriteLine(name);
        Console.WriteLine(age);
        Console.WriteLine(nationality);

        city = "London";
        Console.WriteLine(city);
    }
}
</pre>

<p>
In the above example, we work with four variables. 
</p>

<pre class="explanation">
string city = "New York";
</pre>

<p>
We declare a city variable of the string type and
initialize it to the "New York" value.
</p>

<pre class="explanation">
string name = "Paul"; int age = 35;
</pre>

<p>
We declare and initialize two more variables.
We can put two statements into one line. But for
readability reasons, each statement should be on
a separate line. 
</p>

<pre class="explanation">
Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);
</pre>

<p>
We print the values of the variables to the terminal.
</p>

<pre class="explanation">
city = "London";
</pre>

<p>
We assign a new value to the city variable. 
</p>

<pre>
$ ./variables.exe 
New York
Paul
35
American
London
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
<b>Constants</b> As we already said above, constants cannot change their
initial values. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        const int WIDTH = 100;
        const int HEIGHT= 150;
        int var = 40;

        var = 50;

        // WIDTH = 110;
    }
}
</pre>

<p>
In this example, we declare two constants and one variable.
</p>

<pre class="explanation">
const int WIDTH = 100;
const int HEIGHT= 150;
</pre>

<p>
We use the <code>const</code> keyword
to inform the compiler, that we declare a constant. It
is a convention to write constants in upper case letters.
</p>

<pre class="explanation">
int var = 40;

var = 50;
</pre>

<p>
We declare and initialize a variable. Later, we assign a new value
to the variable. It is legal. 
</p>

<pre class="explanation">
// WIDTH = 110;
</pre>

<p>
This is not possible with a constant. If we uncomment this line,
we will get a compilation error. 
</p>



<h2>Variable interpolation</h2>

<p>
<b>Variable interpolation</b> is replacing
variables with their values inside string literals.
Another names for variable interpolation are: variable 
substitution and variable expansion.
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        int age = 34;
        string name = "William";
        string output;

        output = string.Format("{0} is {1} years old.", 
            name, age);
        Console.WriteLine(output);
    }
}
</pre>

<p>
In C#, strings are immutable. We cannot modify an existing
string. Variable interpolation happens during string creation. 
</p>

<pre class="explanation">
int age = 34;
string name = "William";
string output;
</pre>

<p>
Here we declare three variables. 
</p>

<pre class="explanation">
output = string.Format("{0} is {1} years old.", 
    name, age);
</pre>

<p>
We use the <code>Format()</code> method of the
built-in string class. The {0}, {1} are the places, where
the variables are evaluated. The numbers represent the 
position of the variable. {0} evaluates to the first
supplied variable, {1} to the second etc.
</p>

<pre>
$ ./interpolation.exe 
William is 34 years old.
</pre>

<p>
Output.
</p>


<p>
This chapter covered some basics of the C# language.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 13, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

